package com.lixixi.tingshu.album.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lixixi.tingshu.album.service.AlbumInfoService;
import com.lixixi.tingshu.common.constant.KafkaConstant;
import com.lixixi.tingshu.common.constant.RedisConstant;
import com.lixixi.tingshu.model.album.AlbumInfo;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AlbumFlushBloomFilterListener {
	@Autowired
	RedissonClient redissonClient;

	@Autowired
	AlbumInfoService albumInfoService;

	@KafkaListener(groupId = "albumFlushBloomFilterListener", topics = KafkaConstant.QUEUE_ALBUM_FLUSH_BLOOM_FILTER)
	void albumFlushBloomFilterListener(){
		//初始化专辑布隆过滤器
		RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
		//设置数据规模 误判率 预计统计元素数量为100000，期望误差率为0.01
		bloomFilter.tryInit(100000, 0.01);
		//重新部署布隆过滤器
		List<AlbumInfo> list = albumInfoService.list(new LambdaQueryWrapper<AlbumInfo>().select(AlbumInfo::getId));
		if(list != null){
			list.forEach(albumInfo -> bloomFilter.add(albumInfo.getId()));
		}
	}
}
